from rules.peaces.AbstractPeace import AbstractPeace;
from core import Utils;
from core import PlayerColor;
from core.PeacePosition import PeacePosition;
from core import PeaceType;
from core import Utils;

class GetmanPeace(AbstractPeace):

    def __init__(self, controller, type):
        AbstractPeace.__init__(self, controller, type);
        self._isNobel = False;
        self._limit = 8;

    def checkMotion(self, sP, fP):
        targetCell = self._controller.boardData.getPeaceByCell(fP);
        if(Utils.getPeaceColor(targetCell) == self._getMyColor()):
            return False;
        return self._checkHorizontalMotion(sP, fP) or self._checkTraverseMotion(sP, fP);

    def _checkHorizontalMotion(self, sP, fP):

        if(sP.x == fP.x):
            dY = sP.y - fP.y;
            if abs(dY) > self._limit:
                return False;
            dirY = dY / abs(dY);
            lst = range(sP.y, fP.y, -dirY);
            lst = lst[1:len(lst)];
            for cY in lst:
                pos = PeacePosition(sP.x, cY);
                pType = self._controller.boardData.getPeaceByCell(pos);
                if(pType != PeaceType.BLANK_CELL) or (self._illegalMoveOverTron(pos)):
                    return False;
            return True;
        elif(sP.y == fP.y):
            dX = sP.x - fP.x;
            if abs(dX) > self._limit:
                return False;
            dirX = dX / abs(dX);
            lst = range(sP.x, fP.x, -dirX);
            lst = lst[1:len(lst)];
            for cX in lst:
                pos = PeacePosition(cX, sP.y);
                pType = self._controller.boardData.getPeaceByCell(pos);
                if(pType != PeaceType.BLANK_CELL) or (self._illegalMoveOverTron(pos)):
                    return False;
            return True;
        else:
            return False;

    def _checkTraverseMotion(self, sP, fP):
        dX = sP.x - fP.x;
        dY = sP.y - fP.y;
        if(abs(dX) == abs(dY) and abs(dX) <= self._limit):
            dirX = dX / abs(dX);
            dirY = dY / abs(dY);
            lst = range(abs(dX));
            for count in lst[1:len(lst)]:
                pos = PeacePosition(sP.x - dirX * count, sP.y - dirY * count);
                currentCell = self._controller.boardData.getPeaceByCell(pos);
                if(currentCell != PeaceType.BLANK_CELL) or (self._illegalMoveOverTron(pos)):
                    return False;
            return True
        return False;

    def _illegalMoveOverTron(self, pos):
        return self._isNobel != True and pos.x == 4 and pos.y == 4;